package com.wxxymaker.utils;

import com.blade.kit.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedList;
import java.util.List;

/**
 * @Author: Soft
 * @Date: 2018/6/14 18:25
 * @Desc: 数组工具 主要用来二维码中公司id数组的加密和解密
 */
public class ArrayUtils {
    private final static Logger log = LoggerFactory.getLogger(ArrayUtils.class);
    private static String sp = "_";

    /**
     * 将数组加密为base64
     * @param ids  待加密数组
     * @return    hex字符串
     */
    public static String toHexString(Integer[] ids) {
        if (ids.length > 0) {
            StringBuilder builder = new StringBuilder();
            for (Integer o : ids) {
                builder.append(o).append(sp);
            }
            return Base64.encodeToString(builder.toString().getBytes(), Base64.NO_WRAP);
        }
        return "";
    }

    /**
     * 解密base64字符串为int数组
     * @param hex  加密字符串
     * @return     int数组
     */
    public static Integer[] fromHexString(String hex) throws Exception {
        if (hex != null && !"".equals(hex)) {
            byte[] decode  = Base64.decode(hex.getBytes(), Base64.NO_WRAP);
            String ds      = new String(decode);
            String[] split = ds.split(sp);
            List<Integer> ids = new LinkedList<>();
            for (String s : split) {
                ids.add(Integer.parseInt(s));  // 这里的异常上抛
            }
            if (ids.size() > 0) {
                return ids.toArray(new Integer[ids.size()]);
            }
        }
        return null;
    }
}
